<template>
  <el-dialog
    :title="dialog.title"
    :visible.sync="dialog.show"
    width="600px"
    custom-class="mydialog"
    append-to-body
    @close="handleClose"
  >
    <div class="dialog-content">
      <el-form ref="form1" :model="form" :rules="rules" label-width="150px">
        <el-form-item :rules="[{required: true, message: '仓库不能为空', trigger: 'blur' }]" label="仓库">
          <el-select v-model="warehouseId" placeholder="请选择仓库" style="width: 250px;" filterable>
            <el-option
              v-for="warehouse in warehouseList"
              :label="warehouse.warehouseName"
              :value="warehouse.warehouseId"
              :key="warehouse.warehouseId"
              :disabled="warehouse.disabled"
            />
          </el-select>
        </el-form-item>

        <el-form-item
          :rules="[{required: true, message: '出入方式不能为空', trigger: 'blur' }]"
          label="出入方式"
        >
          <el-select v-model="inventoryType" placeholder="请选出入方式" style="width: 250px;" filterable>
            <el-option
              v-for="inventoryType in inventoryTypeList"
              :label="inventoryType.name"
              :value="inventoryType.id"
              :key="inventoryType.id"
            />
          </el-select>
        </el-form-item>
        <el-form-item label="备注">
          <el-input v-model="remark"/>
        </el-form-item>

        <el-table :data="tableData" :key="index" border style="width: 100%" class="dialog-table">
          <el-table-column label="操作" fixed="left" property width="100">
            <template slot-scope="scope">
              <el-button
                icon="el-icon-plus"
                type="text"
                size="small"
                @click.native.prevent="addRow(scope.$index+1)"
              />

              <el-button
                icon="el-icon-delete"
                type="text"
                size="small"
                @click.native.prevent="deleteRow(scope.$index, tableData)"
              />
            </template>
          </el-table-column>

          <el-table-column property="skuCode" label="SKU编号">
            <template slot-scope="scope">
              <el-select
                v-model="scope.row.skuCode"
                :remote-method="remoteMethod"
                :loading="loading"
                filterable
                remote
                reserve-keyword
                placeholder="输入sku编号"
                @change="changeSku(scope.row.skuCode)"
              >
                <el-option
                  v-for="item in options"
                  :key="item"
                  :label="item.skuCode"
                  :value="item.skuCode"
                />
              </el-select>
            </template>
          </el-table-column>

          <el-table-column property="skuName" label="SKU名称">
            <template slot-scope="scope">
              <el-input v-model="scope.row.skuName" disabled="disabled"/>
            </template>
          </el-table-column>

          <el-table-column property="quantityAdjusted" label="数量">
            <template slot-scope="scope">
              <el-input
                v-model="scope.row.quantityAdjusted"
                type="number"
                min-width="10px"
                size="small"
                class="cnt-class"
                @keyup.native="number(scope.row)"
                @change="number(scope.row)"
              />
            </template>
          </el-table-column>
        </el-table>
      </el-form>
      <div class="text-center mt-30">
        <el-button class="greenbt" type="primary" @click="addAdjustmentSheetAndDetails">保存</el-button>
      </div>
    </div>
  </el-dialog>
</template>
<script>
import { skuList } from '@/api/pas/outStock'
import { addAdjustmentSheetAndDetails } from '@/api/pas/adjustment'
import { queryList } from '@/api/pas/warehouse'
export default {
  props: {
    // 父组件调用时传进来的参数
    modalData: {
      type: Object,
      default: () => {}
    }
  },
  data() {
    return {
      options: [],
      selectOption: {},
      dialog: {
        title: '',
        show: true
      },
      loading: false,
      warehouseId: null,
      inventoryType: null,
      inventoryTypeList: [
        { id: 1, name: '出库' },
        { id: 2, name: '入库' },
        { id: 3, name: '转残次品' }
      ],
      warehouseList: [],
      form: {
        type_options: [],
        type: '',
        number: ''
      },
      remark: null,
      rules: {},
      tableData: [
        {
          skuCode: '',
          skuName: '',
          quantityAdjusted: '1'
        }
      ],
      tableRow: {
        skuCode: '',
        skuName: '',
        quantityAdjusted: '1'
      }
    }
  },
  created() {
    this.queryAllWarehouse()
  },
  methods: {
    handleClose() {
      this.$emit('close')
    },
    deleteRow(index, rows) {
      if (index !== 0) {
        rows.splice(index, 1)
      }
    },
    addRow(index) {
      var dTable = 'table' + index
      dTable = { skuCode: '', skuName: '', quantityAdjusted: '1' }
      this.tableData.push(dTable)
    },
    remoteMethod(query) {
      //
      if (query !== '' && query !== null) {
        this.loading = true
        debugger
        this.getSkuList(query)
        setTimeout(() => {
          this.loading = false
        }, 200)
      } else {
        this.loading = false
        this.options = []
      }
    },
    changeSku(value) {
      // 当前选择行
      // 远程获取的参数 options
      for (let index = 0; index < this.options.length; index++) {
        if (this.options[index].skuCode === value) {
          var skuName = this.options[index].skuName
          for (let index = 0; index < this.tableData.length; index++) {
            if (this.tableData[index].skuCode === value) {
              this.tableData[index].skuName = skuName
            }
          }
        }
      }
    },
    test() {
      for (let index = 0; index < this.tableData.length; index++) {
        this.tableData[index].warehouseId = this.warehouseId
        this.tableData[index].inventoryType = this.inventoryType
        this.tableData[index].remark = this.remark
      }
      console.log(JSON.stringify(this.tableData))
    },
    getSkuList(query) {
      var data = {
        search: query
      }
      skuList(data)
        .then(response => {
          if (response.data.status === 'success') {
            this.options = response.data.data.skuList
          } else {
            this.options = []
          }
        })
        .catch(error => {
          this.$message({
            message: '查询sku失败',
            type: 'warning'
          })
          this.listLoading = false
          console.log(error)
        })
    },
    addAdjustmentSheetAndDetails() {
      for (let index = 0; index < this.tableData.length; index++) {
        this.tableData[index].storeId = this.warehouseId
        this.tableData[index].adjustmentType = this.inventoryType
        this.tableData[index].remark = this.remark
        if (!this.tableData[index].skuName) {
          this.$message({
            message: 'sku不能为空',
            type: 'warning'
          })
          return
        }
      }
      if (!this.tableData[0].storeId) {
        this.$message({
          message: '请选择仓库',
          type: 'warning'
        })
        return
      }
      if (!this.tableData[0].adjustmentType) {
        this.$message({
          message: '请选择出入方式',
          type: 'warning'
        })
        return
      }
      // 提交集合表单
      console.log('===========' + JSON.stringify(this.tableData))
      this.detailsJson = JSON.stringify(this.tableData)

      var formData = new FormData()
      formData.append('detailsJson', this.detailsJson)
      addAdjustmentSheetAndDetails(formData)
        .then(response => {
          debugger
          if (response.data.status === 'success') {
            this.$message({
              message: '添加调整单成功',
              type: 'success'
            })
            setTimeout(() => {
              this.handleClose()
            }, 1.5 * 1000)
          } else {
            this.$message({
              message: '添加调整单失败：' + response.data.messge,
              type: 'error'
            })
          }
        })
        .catch(error => {
          console.log(error)
        })
    },
    queryAllWarehouse() {
      var data = {
        deteleFlag: 'N'
        // isRange: 'YES'
      }
      queryList(data)
        .then(response => {
          if (response.data.status === 'success') {
            this.warehouseList = response.data.data.list
            if (this.warehouseList) {
              for (let index = 0; index < this.warehouseList.length; index++) {
                if (this.warehouseList[index].warehouseName === '中转仓') {
                  this.warehouseList[index].disabled = true
                } else {
                  this.warehouseList[index].disabled = false
                }
              }
            }
          }
        })
        .catch(error => {
          console.log(error)
        })
    },
    number(row) {
      debugger
      if (row.quantityAdjusted < 0) {
        row.quantityAdjusted = Math.abs(row.quantityAdjusted)
      } else if (row.quantityAdjusted > 0) {
        row.quantityAdjusted = Math.abs(row.quantityAdjusted)
      } else {
        row.quantityAdjusted = 0
      }
    }
  }
}
</script>

<style>
.mydialog .dialog-table .el-input__inner,
.mydialog .dialog-table .el-input {
  width: 130px;
}
.cnt-class > .el-input__inner {
  width: 80px !important;
  text-align: center;
}
</style>

